package com.wd.mylibrary_live.view.fragment
import android.Manifest
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.media.MediaPlayer
import android.os.Build
import android.view.Gravity
import android.view.LayoutInflater
import android.view.SurfaceView
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.PopupWindow
import android.widget.TextView
import android.widget.Toast
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.wd.mylibrary_base.base.BaseFragment
import com.wd.mylibrary_base.bean.OpenLiveBean
import com.wd.mylibrary_base.utils.MyApp
import com.wd.mylibrary_live.R
import com.wd.mylibrary_live.view.activity.LiveActivity
import com.wd.mylibrary_live.databinding.FragmentLiveBinding
import com.wd.mylibrary_live.view.activity.MusicActivity
import com.wd.mylibrary_live.viewmodel.LiveViewModel
import io.agora.rtc2.ChannelMediaOptions
import io.agora.rtc2.Constants
import io.agora.rtc2.IRtcEngineEventHandler
import io.agora.rtc2.RtcEngine
import io.agora.rtc2.RtcEngineConfig
import io.agora.rtc2.video.VideoCanvas
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream


class LiveFragment : BaseFragment<LiveViewModel,FragmentLiveBinding>(R.layout.fragment_live) {
    private val appId = "e394d3be4df34e1d9f8b67bc5a007de7"
    ////289cbed5b4d342f48b00dcddfe6e889f
    // 填写频道名
    private val channelName = "zhiBo"

    // 填写声网控制台中生成的临时 Token
    private val token =  ""
    private  lateinit var mRtcEngine: RtcEngine
    private var file: File?=null
    var labsOpenLive : OpenLiveBean.LiveData?=null
    //创建MediaPlayer对象
    var  mediaPlayer: MediaPlayer = MediaPlayer()


    override fun initView() {
        MyApp.sp.edit().remove("musicLinks")
            .remove("musicName")
            .commit()
        //申请权限
        initCamera()
        //启用视频模块
        initVideoDg()
        //设置定位
//        setLocation()
//        if (MMKVUtil.flag==false){
//            binding.startLiveId.visibility= View.GONE
//            //调用实名认证弹窗
//            showPopuWindow()
//        }else{
//            binding.startLiveId.visibility= View.VISIBLE
//        }
        //封面图片
        dataBinding.coverImageLiveId.setImageResource(R.mipmap.updata).apply {
            RequestOptions.bitmapTransform(RoundedCorners(20))
        }
        dataBinding.coverImageLiveId.setOnClickListener {
            val intent=Intent(Intent.ACTION_PICK)
            intent.type="image/*"
            startActivityForResult(intent,1001)
        }

        //开播
        dataBinding.startLiveId.setOnClickListener {
            var name_my=dataBinding.titleTextLiveId.text.toString()
            if (name_my.isEmpty()||name_my==null){
                name_my="瑟利姆"
//                Toast.makeText(context,"请输入标题",Toast.LENGTH_SHORT).show()
//                return@setOnClickListener
            }
            var myuser=MyApp.sp.getInt("userId",0)
            var mysession=MyApp.sp.getString("sessionId","")

            if (file==null){
                //设置封面图片
                val intent=Intent(Intent.ACTION_PICK)
                intent.type="image/*"
                startActivityForResult(intent,1001)
            }else{
                //4221,"17271644478834221"
                viewModel.postOpenLive(myuser,mysession.toString(),name_my,file!!)
                startActivity(Intent(activity, LiveActivity::class.java))

            }
        }
        //开播结果返回
        viewModel.openLiveData.observe(this){it->
            Toast.makeText(context,it.message,Toast.LENGTH_SHORT).show()

            if ("0000"!=it.status){
                ToastUtils.showShort(it.message ?: "直播失败")
//                if (it.liveData!=null){
//
//                    val liveData = it.  liveData.liveRtmpUrl
//                    val split = liveData.split("pwd=")
//                    var pwd=RsaCoder.encryptByPublicKey(RsaCoder.decryptByPublicKey(split[1]))
//                    mStreamer.url=split[0]+"pwd="+pwd?.replace("/".toRegex(),"-")?.replace("\\+".toRegex(),"~")
//                    mStreamer.startStream()
//                }

            }else{

                it.liveData.let {
                        it1->
                    if (it1!=null){
                        labsOpenLive=it1
                        MyApp.sp.edit().putString("agoraToken",it1.agoraToken)
                            .putString("channelName",it1.channelName)
                            .putInt("liveId",it1.liveId)
                            .putString("compositeWsUrl",it1.compositeWsUrl)
                            .commit()

//                        MMKVUtil.setLive(labsOpenLive!!.agoraToken,labsOpenLive!!.compositeWsUrl,labsOpenLive!!.channelName)
                        startActivity(Intent(activity,LiveActivity::class.java).apply {
                            putExtra("liveId",labsOpenLive!!.liveId)
                        })

                    }
                }
            }
        }

        //前后摄像头切换
        dataBinding.liveFlip.setOnClickListener {
            mRtcEngine.switchCamera()
        }

        //选择音乐
        dataBinding.musicLiveId.setOnClickListener {
            startActivity(Intent(activity, MusicActivity::class.java))
        }

    }

    override fun dataObserve() {

    }
    //申请权限
    private fun initCamera(): Array<String> {
        //获取权限
//        requestPermissions(
//            arrayOf(
//                android.Manifest.permission.CAMERA,
//                android.Manifest.permission.READ_MEDIA_IMAGES,
//                android.Manifest.permission.WRITE_EXTERNAL_STORAGE,
//                android.Manifest.permission.RECORD_AUDIO,
//                android.Manifest.permission.READ_EXTERNAL_STORAGE,
//                android.Manifest.permission.READ_CALENDAR ,
//
//            ), 10
//        )
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            arrayOf(
                Manifest.permission.RECORD_AUDIO,  // 录音权限
                Manifest.permission.CAMERA,  // 摄像头权限
                Manifest.permission.READ_PHONE_STATE,  // 读取电话状态权限
                Manifest.permission.BLUETOOTH_CONNECT // 蓝牙连接权限
            )
        } else {
            arrayOf(
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA
            )
        }
    }

     private val mRtcEventHandler:IRtcEngineEventHandler=object :IRtcEngineEventHandler(){
         override fun onUserJoined(uid: Int, elapsed: Int) {
            com.blankj.utilcode.util.ThreadUtils.runOnUiThread(kotlinx.coroutines.Runnable { uid })

         }
     }
    //视频模块
    private fun initVideoDg(){
        try {
            val config=RtcEngineConfig()
            config.mContext=requireActivity()
            config.mAppId = appId;
            config.mEventHandler = mRtcEventHandler;
            // 创建并初始化 RtcEngine
            mRtcEngine = RtcEngine.create(config);
        }catch (e:Exception){

        }
        val  container:FrameLayout=dataBinding.localVideoViewContainer
        val surfaceView = SurfaceView(context)
        container.addView(surfaceView);
        // 将 SurfaceView 对象传入声网实时互动 SDK，设置本地视图
        mRtcEngine.setupLocalVideo(VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, 0))

        // 创建 ChannelMediaOptions 对象，并进行配置
        val options = ChannelMediaOptions()
        // 设置用户角色为 BROADCASTER (主播) 或 AUDIENCE (观众)
        options.clientRoleType = Constants.CLIENT_ROLE_BROADCASTER
        // 设置频道场景为 BROADCASTING (直播场景)
        options.channelProfile = Constants.CHANNEL_PROFILE_LIVE_BROADCASTING

    }
    //实名认证弹窗
//    private fun showPopuWindow(){
//        val view = LayoutInflater.from(context).inflate(R.layout.item_dialog_msg,null)
//        val popWnd= PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
//            ViewGroup.LayoutParams.WRAP_CONTENT,true)
//        popWnd.contentView=view
//        //设置位置
//        popWnd.showAtLocation(view, Gravity.CENTER,0,0)
//        val sum2=view.findViewById<TextView>(R.id.live_dialog_false_id)
//        sum2.setOnClickListener {
//            popWnd.dismiss()
//            Toast.makeText(context,"您未实名认证,暂时无法开通直播功能", Toast.LENGTH_SHORT).show()
//        }
//        val sum1=view.findViewById<TextView>(R.id.live_dialog_true_id)
//        sum1.setOnClickListener {
//            startActivity(Intent(context,RealNameActivity::class.java))
//
//        }
//    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data!=null){
            if (requestCode==1001&&data.data!=null){
                val openInputStream=requireActivity().contentResolver
                    .openInputStream(data.data!!)
                val bitmap= BitmapFactory.decodeStream(openInputStream)
                if (file!=null){
                    file=null
                }
                file=File("${requireActivity().externalCacheDir}"+File.separator+"endimg.jpg")
                if (!file!!.exists()){
                    file!!.createNewFile()
                }
                val bufferedOutputStream= BufferedOutputStream(FileOutputStream(file))
                bitmap.compress(Bitmap.CompressFormat.JPEG,20,bufferedOutputStream)
                Glide.with(requireActivity()).load(file).into(dataBinding.coverImageLiveId)
            }
        }
    }
    override fun onResume() {
        super.onResume()
        // 启用视频模块
        mRtcEngine?.enableVideo()
        // 开启本地预览
        mRtcEngine?.startPreview()

        val name = MyApp.sp.getString("musicName", "选择音乐")
        dataBinding.musicLiveId.text=name
        //播放音乐
        val musicLinks = MyApp.sp.getString("musicLinks", "") as String
        if (musicLinks!==null &&  musicLinks!==""){
            mediaPlayer.reset()
            mediaPlayer.setDataSource(musicLinks)
            mediaPlayer.prepare()
            mediaPlayer.start()
        }

    }

    override fun onPause() {
        super.onPause()
        mediaPlayer.stop()
    }

    override fun onStop() {
        super.onStop()
        mediaPlayer.stop()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (mRtcEngine != null) {
            // 停止本地视频预览
            mRtcEngine!!.stopPreview()
            // 离开频道
            mRtcEngine!!.leaveChannel()
//            mRtcEngine = null
//            // 销毁引擎
//            RtcEngine.destroy()
        }
    }


}